import uuid

import pymysql
from pymysql.cursors import DictCursor


# 批量刷写用户权限菜单的父级菜单
def process_role_permissions(db_config):
    """
    处理角色权限，确保父权限也被添加到角色权限表中
    :param db_config: 数据库连接配置字典
    """
    try:
        # 连接数据库
        connection = pymysql.connect(**db_config, cursorclass=DictCursor)

        with connection.cursor() as cursor:
            # 第一步：查询sys_role_permission表中所有权限
            cursor.execute("""
                select id,
                       role_id,
                       permission_id,
                       tenant_id,
                       remark,
                       deleted_tag,
                       create_user,
                       create_user_name,
                       create_date,
                       change_user,
                       change_user_name,
                       change_date
                from sys_role_permission
            """)
            role_permissions = cursor.fetchall()

            num_n = 0
            num_y = 0
            # 第二步：为每个权限检查是否有父权限
            for row in role_permissions:
                # 查询当前权限是否有父权限
                cursor.execute("SELECT parent_id FROM sys_permission WHERE id = %s", (row['permission_id'],))
                result = cursor.fetchone()

                if result and result['parent_id']:  # 如果有父权限
                    parent_id = result['parent_id']
                    role_id = row['role_id']

                    # 检查是否已存在相同的role_id和parent_id记录
                    cursor.execute(
                        "SELECT COUNT(*) cnt FROM sys_role_permission WHERE role_id = %s AND permission_id = %s",
                        (role_id, parent_id)
                    )
                    count = cursor.fetchone()['cnt']

                    if count == 0:  # 如果不存在则插入
                        row['id'] = str(uuid.uuid4())
                        row['parent_id'] = parent_id
                        cursor.execute(
                            """
                            INSERT INTO sys_role_permission (id, role_id, permission_id,tenant_id,remark,deleted_tag,
                                   create_user,create_user_name,create_date,change_user,change_user_name,change_date)
                                    VALUES (%(id)s, %(role_id)s, %(parent_id)s, %(tenant_id)s, %(remark)s, 
                                    %(deleted_tag)s, %(create_user)s, %(create_user_name)s, %(create_date)s, 
                                    %(change_user)s,%(change_user_name)s, %(change_date)s)
                            """,
                            row
                        )
                        print(f"已为角色 {role_id} 添加父权限 {parent_id}")
                        num_n += 1
                    else:
                        print(f"角色 {role_id} 已有权限 {parent_id}，跳过插入")
                        num_y += 1

            # 提交事务
            connection.commit()
            print(f"处理完成, 新加权限{num_n}, 已有权限{num_y}")

    except Exception as e:
        print(f"发生错误: {e}")
        if 'connection' in locals():
            connection.rollback()
    finally:
        if 'connection' in locals() and connection.open:
            connection.close()


# 数据库配置
db_config = {
    'host': '10.99.81.155',
    'port': 8306,
    'user': 'jg_usercenter',
    'password': 'Jg_usercenter_20250312',
    'database': 'jg_usercenter',
    'charset': 'utf8mb4'
}

# 执行处理
if __name__ == '__main__':
    process_role_permissions(db_config)
